<?php
	include("cronDB.config.php");
	include($WEBSITE_DOCUMENT_ROOT."/CommonClasses/user.class.php");
	
	$fileName = "logs/SIGNUP_EMAILS_".strtoupper(date('dMo_Hi')).".log";
	$fileHandle = fopen($fileName,"w");

	writeLogMessage("File " . $fileName .  " Open and Ready for Writing", $fileHandle);
		
	$sql = "select concat(u.firstname,\" \",u.lastname) as fullname, u.username,signup_datetime,email from lwbc_main.signups su
			join lwbc_main.users u on su.username = u.username
			where su.email_user = 1
        		and su.signup_datetime > curdate()
        		and date_add(curdate(),interval 7 day) = date(su.signup_datetime)
        		and event_id = 1000000";
	
	$DB->query($sql);
	
	writeLogMessage("Query Executed - " . $DB->get_num_rows() . " Rows Returned", $fileHandle);
	
	while($row = $DB->fetch_row()) {
		if(emailUser($row['fullname'],$row['username'],$row['email'], $row['signup_datetime'])) {
			writeLogMessage("Success - Email Sent to " . $row['email'], $fileHandle);
		}
		else {
			writeLogMessage("Failure - Email Sent to " . $row['email'], $fileHandle);
		}
	}
	
	writeLogMessage("All Emails Sent", $fileHandle);
	
	fclose($fileHandle);
	
	function emailUser($fullName,$username,$emailAddress,$signUpDate) {
		$dateSignUp = strtotime($signUpDate);
		
		$emailText = $fullName . ",\n\n";
		$emailText .= "This is your reminder!\n\n";
		$emailText .= "You signed up for the Prayer Campaign to pray on " . date('l, F j, Y g:i A', $dateSignUp) . ".\n\n";
		$emailText .= "Thank you for partnering with us in this ministry.\n\n";
		$emailText .= "If you are recieving this email in error or if any informaiton in it is wrong, then feel free to email project672@lwbc.net.\n\n";
		$emailText .= "A lock box is by the side door at the front of the church, where the new ground lights have been installed.\n";
		$emailText .= "The code (#4130) will give access through this door.  If you forget the code, just call the church number,\n";
		$emailText .= "434-525-7736  and the number 6.  The code will be available at this extension.\n\n";
		$emailText .= "Living Word Online\n(434) 525-7736\n";
			
		if(mail($emailAddress ,"Sign Up Reminder",$emailText,"From: Living Word Baptist Church <admin@lwbc.net>" . "\r\n" . "Reply-To: admin@lwbc.net")) {
			return true;
		}
		else {
			return false;
		}
	}
	
	function writeLogMessage($message, $fileHandle) {
		$message = date("d-M-o H:i:s") . "   -   " . $message . "\r\n";
		print $message;
		fwrite($fileHandle, $message);
	}
?>